unit uSearches;
interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, ShoppingServiceXMLClasses, StdCtrls, DB,
  EbayConnect, ExtCtrls, DBCtrls,
   uEbaySearchThread,   cxGraphics, cxControls, cxLookAndFeelPainters,
  cxContainer, cxDBEdit,  cxEdit, cxDropDownEdit, cxCalendar,
  cxGroupBox, cxRadioGroup, cxCheckBox, cxMemo, cxTextEdit, cxMaskEdit,
  cxSpinEdit,  cxDataStorage, cxDBData, cxGridCustomTableView, cxGridTableView,
  cxGridBandedTableView, cxGridDBBandedTableView, cxGridCustomView,
  cxGridLevel, cxGrid, cxTL, cxTLdxBarBuiltInMenu,
  cxInplaceContainer,  cxDBLookupComboBox, dxtree,
  ImgList, ComCtrls, cxLookupEdit,  cxDBLookupEdit, cxClasses, cxCheckGroup,
  cxDBCheckGroup, cxGridDBTableView, nxdb, siComp, cxDBTL,
  cxTLData, cxLabel, cxLookAndFeels, cxStyles, cxCustomData, cxFilter, cxData,
  dxSkinsCore, dxSkinBlack, dxSkinBlue, dxSkinCaramel, dxSkinCoffee,
  dxSkinDarkRoom, dxSkinDarkSide, dxSkinFoggy, dxSkinGlassOceans,
  dxSkiniMaginary, dxSkinLilian, dxSkinLiquidSky, dxSkinLondonLiquidSky,
  dxSkinMcSkin, dxSkinMoneyTwins, dxSkinOffice2007Black, dxSkinOffice2007Blue,
  dxSkinOffice2007Green, dxSkinOffice2007Pink, dxSkinOffice2007Silver,
  dxSkinPumpkin, dxSkinSeven, dxSkinSharp, dxSkinSilver, dxSkinSpringTime,
  dxSkinStardust, dxSkinSummer2008, dxSkinsDefaultPainters, dxSkinValentine,
  dxSkinXmas2008Blue, dxSkinscxPCPainter, uTypes;

type

  TfmSearches = class(TForm)
    dsSearches: TDataSource;
    Label1: TLabel;
    Label2: TLabel;
    il1: TImageList;
    dbtxtCategoryName: TDBText;
    lbl1: TLabel;
    lbl2: TLabel;
    lbl5: TLabel;
    lbl6: TLabel;
    lbl7: TLabel;
    lbl8: TLabel;
    lbl13: TLabel;
    lbl15: TLabel;
    lbl18: TLabel;
    lbl19: TLabel;
    lbl20: TLabel;
    lbl21: TLabel;
    lbl22: TLabel;
    bvl2: TBevel;
    lbl23: TLabel;
    lbl24: TLabel;
    lbl25: TLabel;
    dsCountries: TDataSource;
    lbl26: TLabel;
    cxDBSpinEdit1: TcxDBSpinEdit;
    cxDBSpinEdit2: TcxDBSpinEdit;
    cxDBSpinEdit3: TcxDBSpinEdit;
    cxDBSpinEdit4: TcxDBSpinEdit;
    cxDBSpinEdit5: TcxDBSpinEdit;
    cxDBSpinEdit6: TcxDBSpinEdit;
    cxDBSpinEdit7: TcxDBSpinEdit;
    cxDBSpinEdit8: TcxDBSpinEdit;
    cxDBComboBox1: TcxDBComboBox;
    cxDBComboBox2: TcxDBComboBox;
    cxDBComboBox3: TcxDBComboBox;
    cxDBMemo1: TcxDBMemo;
    cxDBMemo2: TcxDBMemo;
    cxDBTextEdit1: TcxDBTextEdit;
    cxDBComboBox4: TcxDBComboBox;
    cxDBComboBox5: TcxDBComboBox;
    cxDBCheckBox1: TcxDBCheckBox;
    cxDBCheckBox2: TcxDBCheckBox;
    cxDBCheckBox3: TcxDBCheckBox;
    cxDBCheckBox4: TcxDBCheckBox;
    cxDBCheckBox5: TcxDBCheckBox;
    cxDBCheckBox6: TcxDBCheckBox;
    cxDBCheckBox7: TcxDBCheckBox;
    cxDBCheckBox8: TcxDBCheckBox;
    cxDBCheckBox9: TcxDBCheckBox;
    cxDBCheckBox10: TcxDBCheckBox;
    cxDBDateEdit1: TcxDBDateEdit;
    lbl9: TLabel;
    cxDBDateEdit2: TcxDBDateEdit;
    cxDBSpinEdit9: TcxDBSpinEdit;
    cxDBTextEdit2: TcxDBTextEdit;
    cxDBTextEdit3: TcxDBTextEdit;
    dsCategories: TDataSource;
    cxDBLookupComboBox1: TcxDBLookupComboBox;
    cxDBLookupComboBox2: TcxDBLookupComboBox;
    lbl3: TLabel;
    lbl4: TLabel;
    cxDBLookupComboBox3: TcxDBLookupComboBox;
    cxDBCheckGroup1: TcxDBCheckGroup;
    Label3: TLabel;
    cbb1: TcxDBComboBox;
    cxDBMemo3: TcxDBMemo;
    lbl10: TLabel;
    lbl11: TLabel;
    Label4: TLabel;
    cxdbchckbx1: TcxDBCheckBox;
    cxdbchckbx2: TcxDBCheckBox;
    lbl12: TLabel;
    lbl14: TLabel;
    bvl1: TBevel;
    btn1: TButton;
    dsaspects: TDataSource;
    dsaspectvalues: TDataSource;
    cxGrid1Level1: TcxGridLevel;
    cxGrid1: TcxGrid;
    cxGrid1TableView1: TcxGridTableView;
    cxgrdbtblvwGrid1DBTableView1: TcxGridDBTableView;
    cxgrdlvlGrid1Level2: TcxGridLevel;
    cxgrdbtblvwGrid1DBTableView2: TcxGridDBTableView;
    cxgrdbclmnGrid1DBTableView1aspect: TcxGridDBColumn;
    cxgrdbclmnGrid1DBTableView2aspectvalname: TcxGridDBColumn;
    cxgrdbclmnGrid1DBTableView2count: TcxGridDBColumn;
    cxgrdbclmnGrid1DBTableView2selected: TcxGridDBColumn;
    tblaspectvalues: TnxTable;
    IntegerField1: TIntegerField;
    StringField1: TStringField;
    IntegerField2: TIntegerField;
    tblaspectvaluesselected: TBooleanField;
    tblaspects: TnxTable;
    IntegerField3: TIntegerField;
    StringField2: TStringField;
    tblCountries: TnxTable;
    qryCategories: TnxQuery;
    qryCategoriesChildrens: TIntegerField;
    qryCategoriesCategoryName: TStringField;
    qryCategoriesLeafCategory: TBooleanField;
    qryCategoriesCategoryID: TIntegerField;
    qryCategoriesCategoryParentID: TIntegerField;
    qryCategoriesCategoryLevel: TIntegerField;
    tblSearchesenabled: TBooleanField;
    tblSearchesname: TStringField;
    tblSearcheskeywords: TStringField;
    tblSearchesDescriptionSearch: TBooleanField;
    tblSearchesCategoryID: TStringField;
    tblSearchesCategoryName: TStringField;
    tblSearchesAvailableTo: TStringField;
    tblSearchesCondition: TStringField;
    tblSearchesCurrency: TStringField;
    tblSearchesEndTimeFrom: TDateTimeField;
    tblSearchesEndTimeTo: TDateTimeField;
    tblSearchesExcludeAutoPay: TBooleanField;
    tblSearchesExcludeSeller: TStringField;
    tblSearchesFeaturedOnly: TBooleanField;
    tblSearchesFeedbackScoreMax: TIntegerField;
    tblSearchesFeedbackScoreMin: TIntegerField;
    tblSearchesFreeShippingOnly: TBooleanField;
    tblSearchesGetItFastOnly: TBooleanField;
    tblSearchesHideDuplicateItems: TBooleanField;
    tblSearchesListingType: TStringField;
    tblSearchesLocalPickupOnly: TBooleanField;
    tblSearchesLocalSearchOnly: TBooleanField;
    tblSearchesLocatedIn: TStringField;
    tblSearchesLotsOnly: TBooleanField;
    tblSearchesMaxBids: TIntegerField;
    tblSearchesMaxDistance: TIntegerField;
    tblSearchesMaxPrice: TFloatField;
    tblSearchesMaxQuantity: TIntegerField;
    tblSearchesMinBids: TIntegerField;
    tblSearchesMinPrice: TFloatField;
    tblSearchesMinMaxPriceCurrency: TStringField;
    tblSearchesMinQuantity: TIntegerField;
    tblSearchesPaymentMethod: TStringField;
    tblSearchesSeller: TStringField;
    tblSearchesSellerBusinessType: TStringField;
    tblSearchesTopRatedSellerOnly: TBooleanField;
    tblSearchesWorldOfGoodOnly: TBooleanField;
    tblSearchesBuyerPostalCode: TStringField;
    tblSearchesGlobalSiteID: TStringField;
    tblSearchesSortOrder: TStringField;
    tblSearchesApiCallsUsedToday: TIntegerField;
    tblSearchesSearchPeriod: TIntegerField;
    tblSearchesLastSearchStarted: TDateTimeField;
    tblSearchesAutoExpandLeafCategories: TBooleanField;
    slng1: TsiLang;
    tblSearches: TnxTable;
    cxDBCheckBox11: TcxDBCheckBox;
    pnl1: TPanel;
    btn2: TButton;
    btn3: TButton;
    tblCountriesName: TStringField;
    tblCountriesCode: TStringField;
    cxDBTreeList1: TcxDBTreeList;
    cxDBTreeList1cxDBTreeListColumn1: TcxDBTreeListColumn;
    cxDBTreeList1cxDBTreeListColumn2: TcxDBTreeListColumn;
    qryCategoriesileaf: TSmallintField;
    tblSearchesid: TUnsignedAutoIncField;
    tblaspectvaluesid: TUnsignedAutoIncField;
    tblaspectvaluesaspectvalname_translated: TStringField;
    tblaspectsid: TUnsignedAutoIncField;
    tblaspectsaspect_translate: TStringField;
    tmrTranslation: TTimer;
    cxMemo1: TcxMemo;
    Label5: TLabel;
    procedure FormShow(Sender: TObject);
    procedure FormClose(Sender: TObject; var Action: TCloseAction);
    procedure FormCreate(Sender: TObject);
    procedure qryCategoriesCalcFields(DataSet: TDataSet);
    procedure tblSearchesAfterInsert(DataSet: TDataSet);
    procedure tv1DblClick(Sender: TObject);
    procedure tblSearchesGlobalSiteIDChange(Sender: TField);
    procedure dsSearchesDataChange(Sender: TObject; Field: TField);
    procedure tblSearchesAvailableToChange(Sender: TField);
    procedure tblSearchesLocatedInChange(Sender: TField);
    procedure tblSearchesAfterPost(DataSet: TDataSet);
    procedure cxDBMemo3KeyPress(Sender: TObject; var Key: Char);
    procedure btn1Click(Sender: TObject);
    procedure OnFindAdvThreadTerminate(Sender: TObject);
    procedure btn2Click(Sender: TObject);
    procedure btn3Click(Sender: TObject);
    procedure qryCategoriesAfterOpen(DataSet: TDataSet);
    procedure tmrTranslationTimer(Sender: TObject);
    procedure cxDBMemo3PropertiesChange(Sender: TObject);


  private
    { Private declarations }
    Aspectthread : TFindAdvThread;
    procedure OnGTranslateThreadterminate(Sender : TObject);
  public
    { Public declarations }
    Operation : TSOperation;
  end;

var
  fmSearches: TfmSearches;

implementation

uses TypInfo, FindingServiceXMLClasses, uMain, googleTranslator, GTranslate, HotLog;
{$R *.dfm}

procedure TfmSearches.FormShow(Sender: TObject);
begin
  if not tblCountries.Active then tblCountries.Open;
  if not fmMain.qryActiveSites.Active then fmMain.qryActiveSites.Open;
  if not tblaspects.Active then tblaspects.Open;
  if not tblaspectvalues.Active then tblaspectvalues.Open;
  if not tblSearches.Active then tblSearches.Open;
  if Operation=opNew then begin
    tblSearches.Insert;
    tblSearches.FieldByName('GlobalSiteID').AsString := 'EBAY_US';
    tblSearches.FieldByName('name').AsString := 'New search';
    tblSearches.Post;
  end;
  if not qryCategories.Active then qryCategories.Open;
  cxMemo1.Clear;
end;

procedure TfmSearches.FormClose(Sender: TObject; var Action: TCloseAction);
begin
  if qryCategories.Active then qryCategories.Close;
  if tblCountries.Active then tblCountries.Close;
  if tblSearches.Active then tblSearches.Close;
//  Action := caFree;
//  fmSearches := nil;
end;

procedure TfmSearches.FormCreate(Sender: TObject);
var i : Integer;
begin
  cxDBCheckGroup1.Properties.Items.Clear;
  for i:= 0 to Ord(High(CurrencyCodeType)) do cxDBComboBox5.Properties.Items.Add(GetEnumName(TypeInfo(CurrencyCodeType),ord(i)));
  for i:= 0 to Ord(High(CurrencyCodeType)) do cxDBComboBox1.Properties.Items.Add(GetEnumName(TypeInfo(CurrencyCodeType),ord(i)));
  for i:= 0 to Ord(High(ListingTypes)) do  with cxDBCheckGroup1.Properties.Items.Add do Caption := GetEnumName(TypeInfo(ListingTypes),ord(i));
  Operation := opEdit;
end;

procedure TfmSearches.qryCategoriesAfterOpen(DataSet: TDataSet);
begin
  if tblSearches.Active then
  if not tblSearches.FieldByName('CategoryID').IsNull then
  qryCategories.Locate('CategoryID',tblSearches.FieldByName('CategoryID').Value,[]);
end;

procedure TfmSearches.qryCategoriesCalcFields(DataSet: TDataSet);
begin
  if qryCategories.FieldByName('LeafCategory').Value then  qryCategories.FieldByName('Childrens').Value := 0
  else qryCategories.FieldByName('Childrens').Value := 1;
  if qryCategories.FieldByName('LeafCategory').Value then  qryCategories.FieldByName('ileaf').Value :=1
  else qryCategories.FieldByName('ileaf').Value :=0;
end;

procedure TfmSearches.tblSearchesAfterInsert(DataSet: TDataSet);
begin
  tblSearches.FieldByName('GlobalSiteID').Value := 'EBAY_US';
  tblSearches.FieldByName('enabled').Value := true;
end;

procedure TfmSearches.tv1DblClick(Sender: TObject);
begin
  //if tv1.DBSelected.HasChildren then Exit;
  if dsSearches.State in [dsBrowse] then tblSearches.Edit;
  tblSearches.FieldByName('CategoryID').Value := qryCategories.FieldByName('CategoryID').Value;
  tblSearches.FieldByName('CategoryName').Value := qryCategories.FieldByName('CategoryName').Value;
  //tblSearches.Post;
end;

procedure TfmSearches.tblSearchesGlobalSiteIDChange(Sender: TField);
begin
  if tblSearches.FieldByName('GlobalSiteID').Value <> qryCategories.Params[0].Value then begin
    if tblSearches.FieldByName('GlobalSiteID').Value = '' then qryCategories.Params[0].Value := 'EBAY_US'
    else  qryCategories.Params[0].Value := tblSearches.FieldByName('GlobalSiteID').Value;
    qryCategories.Close;
    qryCategories.Open;
  end;
end;

procedure TfmSearches.dsSearchesDataChange(Sender: TObject; Field: TField);
begin
  if dsSearches.State in [dsBrowse] then begin
    if tblSearches.FieldByName('GlobalSiteID').Value <> qryCategories.Params[0].Value then begin
      if tblSearches.FieldByName('GlobalSiteID').Value = '' then qryCategories.Params[0].Value := 'EBAY_US'
      else  qryCategories.Params[0].Value := tblSearches.FieldByName('GlobalSiteID').Value;
      qryCategories.Close;
      qryCategories.Open;
    end;
    if qryCategories.Active then
    if (tblSearches.FieldByName('CategoryID').Value <> '') and not tblSearches.FieldByName('CategoryID').IsNull then
    qryCategories.Locate('CategoryID',StrToInt(tblSearches.FieldByName('CategoryID').Value),[]);
  end;
  btn2.Enabled := dsSearches.State in [dsEdit,dsInsert];
  btn3.Enabled := dsSearches.State in [dsEdit,dsInsert];
end;

procedure TfmSearches.tblSearchesAvailableToChange(Sender: TField);
begin
  cxDBLookupComboBox2.Enabled := tblSearches.FieldByName('AvailableTo').IsNull;
end;

procedure TfmSearches.tblSearchesLocatedInChange(Sender: TField);
begin
  cxDBLookupComboBox1.Enabled := tblSearches.FieldByName('LocatedIn').IsNull;
end;

procedure TfmSearches.tmrTranslationTimer(Sender: TObject);
var thread : TTranslateThread;
    trString: string;
    SourceLang : TLanguageEnum;
    DestLang : TLanguageEnum;
    TagObj : TObject;
begin
  // starting translation thread
  if cxDBMemo3.Focused then begin
    trString := cxDBMemo3.Text;
    SourceLang := lng_en;
    DestLang := fmMain.SecondLang;
    TagObj := cxMemo1;
  end;
  if cxMemo1.Focused then begin
    trString := cxMemo1.Text;
    SourceLang := fmMain.SecondLang;
    DestLang := lng_en;
    TagObj := cxDBMemo3;
  end;
  hLog.Add(Format('{hms} Translation keyword %s',[trString]));
  if Length(trString)>0 then begin
    thread := TTranslateThread.Create(true);
    thread.SourceString := trString;
    thread.SourceLang := SourceLang;
    thread.DestLang := DestLang;
    thread.TagObj := TagObj;
    thread.OnTerminate := OnGTranslateThreadterminate;
    thread.ItemTable := '';
    thread.Run;
  end;
  tmrTranslation.Enabled := False;
end;

procedure TfmSearches.tblSearchesAfterPost(DataSet: TDataSet);
var ebaymotor : Boolean;
begin
  ebaymotor := tblSearches.FieldByName('GlobalSiteID').Value = 'EBAY_MOTOR';
  cxDBCheckBox10.Enabled := ebaymotor;
  cxDBSpinEdit9.Enabled := ebaymotor;
  lbl13.Enabled := ebaymotor;
end;

procedure TfmSearches.btn2Click(Sender: TObject);
begin
  if dsSearches.State in [dsEdit,dsInsert] then tblSearches.Post;
end;

procedure TfmSearches.btn3Click(Sender: TObject);
begin
  if dsSearches.State in [dsEdit,dsInsert] then tblSearches.Cancel;
  if Operation=opNew then tblSearches.Delete;
end;

procedure TfmSearches.cxDBMemo3KeyPress(Sender: TObject; var Key: Char);
begin
  //MessageDlg('changes',mtInformation,[mbOK],0);
end;

procedure TfmSearches.cxDBMemo3PropertiesChange(Sender: TObject);
begin
  tmrTranslation.Enabled := False;
  tmrTranslation.Enabled := True;
end;

procedure TfmSearches.btn1Click(Sender: TObject);
begin
  cxGrid1.Enabled := False;
  btn1.Enabled := False;
  Aspectthread := TFindAdvThread.Create(fmSearches);
  with Aspectthread do begin
    OnTerminate := OnFindAdvThreadTerminate;
    AppID := fmMain.inisettings.AppID;
    OutputSelector := [AspectHistogram,CategoryHistogram];
    fmMain.SetSearchProperties(Aspectthread, fmMain.IniSettings , tblSearches, true);
    fmMain.CurrentOperation := opLoadAspects;
    PBasePath := fmMain.BasePath;
    XMLDebugOutPut := true;
    FetchAllPages :=False;
    IgnoreCategories :=True ;
    ItemsPerPage := 2;
    SaveAspectValues := True;
    SearchID := tblSearches.FieldByName('id').Value;
    Start;
  end;

end;

procedure TfmSearches.OnFindAdvThreadTerminate(Sender: TObject);
begin
  fmMain.CurrentOperation := opIdle;
  tblaspects.Close;
  tblaspects.Open;
  tblaspectvalues.Close;
  tblaspectvalues.Open;
  cxGrid1.Enabled := True;
  btn1.Enabled := True;
  cxgrdbtblvwGrid1DBTableView1.DataController.UpdateData;
  cxgrdbtblvwGrid1DBTableView2.DataController.UpdateData;
end;

procedure TfmSearches.OnGTranslateThreadterminate(Sender: TObject);
begin
  hLog.Add('{hms} Translate thread terminated');
  with Sender as TTranslateThread do
    if TagObj<>nil then begin
      if TagObj.ClassName = 'TcxDBMemo' then with (TagObj as TcxDBMemo) do begin
        Text := ResultString;
        DataBinding.DataSource.DataSet.FieldByName(DataBinding.DataField).AsString := ResultString;
      end;
      if TagObj.ClassName = 'TcxMemo' then (TagObj as TcxMemo).Text := ResultString;
    end;
end;

end.

{

 <?xml version="1.0" encoding="UTF-8"?>
<findItemsIneBayStoresRequest xmlns="http://www.ebay.com/marketplace/search/v1/services">
  <keywords>harry potter</keywords>
  <storeName>Laura_Chen's_Small_Store</storeName>
  <outputSelector>StoreInfo</outputSelector>
  <itemFilter>
    <name>MinPrice</name>
    <value>11.00</value>
    <paramName>Currency</paramName>
    <paramValue>USD</paramValue>
  </itemFilter>
  <itemFilter>
    <name>MaxPrice</name>
    <value>25.00</value>
    <paramName>Currency</paramName>
    <paramValue>USD</paramValue>
  </itemFilter>
  <paginationInput>
    <entriesPerPage>1</entriesPerPage>
  </paginationInput>
</findItemsIneBayStoresRequest>

<?xml version="1.0" encoding="UTF-8"?>
<findItemsAdvancedRequest xmlns="http://www.ebay.com/marketplace/search/v1/services">
  <categoryId>31388</categoryId>
  <outputSelector>AspectHistogram</outputSelector>
  <itemFilter>
    <name>Condition</name>
    <value>Used</value>
  </itemFilter>
  <itemFilter>
    <name>ListingType</name>
    <value>AuctionWithBIN</value>
  </itemFilter>
  <paginationInput>
    <entriesPerPage>2</entriesPerPage>
  </paginationInput>
</findItemsAdvancedRequest>

SELECT * FROM "Categories"
where GlobalSiteID= 'EBAY_US'

SELECT CategoryID, CategoryLevel, CategoryName, CategoryParentID,  LeafCategory, GlobalSiteID
FROM  "Categories"
where GlobalSiteID = :GlobalSiteID
order by CategoryParentID , CategoryName


}
